package softswitch.agi;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.asteriskjava.fastagi.AgiChannel;
import org.asteriskjava.fastagi.AgiException;
import org.asteriskjava.fastagi.AgiRequest;
import org.asteriskjava.fastagi.BaseAgiScript;

import softswitch.model.CallDetail;
import softswitch.ws.CallLogger;
import softswitch.ws.AgiProcessService;
import softswitch.ws.SoftswitchService;
import util.DateUtil;

@Stateless
public class Outbound extends BaseAgiScript {
	
	@EJB
	SoftswitchService softswitchService;
	
	@EJB
	AgiProcessService callProcessService;
	
	DateUtil dateUtil = new DateUtil();
	CallLogger callLogger = new CallLogger();
	
	
	
	public void service(AgiRequest request, AgiChannel channel) throws AgiException {
		
		exec("Ringing");
		
		String uniqueid = request.getUniqueId();
		String accountcode = request.getAccountCode();
		String destination = request.getExtension();
		String callerIdNumber = request.getCallerIdNumber();
		System.out.println(getVariable("SIPCHANINFO(peerip)"));
		System.out.println(getVariable("SIPCHANINFO(recvip)"));
		
		CallDetail calldetail = new CallDetail();
		calldetail.setUniqueid(uniqueid);
		calldetail.setDestination(destination);
		
		callLogger.calllog(calldetail, "DEBUG", "OutboundAGI", "Starting Switching Call");
		
		if(callProcessService.hasValidCircuit(accountcode,calldetail)) {
			
			//setCallerId(validateCallerId(callerIdNumber));
			
			if(callProcessService.hasValidPlan(destination,calldetail)) {
				
				Integer packagStatus = callProcessService.checkPackageStatus(calldetail);				
				if(packagStatus != null ) {					
					if(packagStatus == 1 ) {
						exec("Dial", "SIP/ss7gw1/017107500");
					}
					if(packagStatus == 2 ) {
						streamFile("package-nocredit");
					}				
					if(packagStatus == 3 ) {
						exec("Dial", "SIP/ss7gw1/014111111");
					}						
				}
				else{
					answer();
					streamFile("package-nocredit");
					//exec("Dial", "SIP/ss7gw1/002157986064838");
				}
				
				
				
			}//ifHasValidPlan
			
		}//ifHasValidCircuit
		
		callProcessService.processCallResult(getVariable("DIALSTATUS"),getVariable("DIALEDTIME"),getVariable("ANSWEREDTIME"));
		exec("Hangup");
		
	}//service()
	
			
	

	
}// Class
